package com.video.internationalvideodisplayproject.service;

import com.video.internationalvideodisplayproject.mapper.BlVideoShootReqDtMapper;
import com.video.internationalvideodisplayproject.pojo.BlVideoShootReqDt;
import com.video.internationalvideodisplayproject.pojo.BlVideoShootReqHd;
import com.video.internationalvideodisplayproject.pojo.vo.ThemeInfoVO;
import com.video.internationalvideodisplayproject.pojo.vo.VideoVO;
import com.video.internationalvideodisplayproject.repository.BlVideoShootReqHdRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class VideoService {

    @Autowired
    private BlVideoShootReqHdRepository videoRepository;
    @Autowired
    private BlVideoShootReqDtMapper blVideoShootReqDtMapper;

    public List<VideoVO> getAllVideos() {
        List<BlVideoShootReqHd> headers = videoRepository.findAllActive();

        return headers.stream().map(header -> {
                    List<BlVideoShootReqDt> blVideoShootReqDts = blVideoShootReqDtMapper.selectAllDetailInfoByBillId(header.getBillId());
                    return new VideoVO(header, blVideoShootReqDts);
                }).filter(video -> !video.getVideoUrls().isEmpty()) // 只返回有有效视频的记录
                .collect(Collectors.toList());

//        return videoRepository.findAllActive()
//                .stream()
//                .map(VideoVO::new)
//                .filter(video -> !video.getVideoUrls().isEmpty()) // 只返回有有效视频的记录
//                .collect(Collectors.toList());
    }

    public List<VideoVO> getVideosByCategory(String category) {
        return videoRepository.findByShootCategory(category)
                .stream()
                .map(VideoVO::new)
                .filter(video -> !video.getVideoUrls().isEmpty())
                .collect(Collectors.toList());
    }

    public List<VideoVO> getVideosByTheme(String topicName) {
        return videoRepository.findByTopicName(topicName)
                .stream()
                .map(VideoVO::new)
                .filter(video -> !video.getVideoUrls().isEmpty())
                .collect(Collectors.toList());
    }

    public List<VideoVO> searchVideos(String keyword) {
        return videoRepository.searchByKeyword(keyword)
                .stream()
                .map(VideoVO::new)
                .filter(video -> !video.getVideoUrls().isEmpty())
                .collect(Collectors.toList());
    }

    public List<VideoVO> searchVideosByCategory(String category, String keyword) {
        return videoRepository.findByCategoryAndKeyword(category, keyword)
                .stream()
                .map(VideoVO::new)
                .filter(video -> !video.getVideoUrls().isEmpty())
                .collect(Collectors.toList());
    }

    public Map<String, Object> getVideoStatistics() {
        List<BlVideoShootReqHd> allVideos = videoRepository.findAllActive();

        // 统计每个分类的视频数量（包含多个视频文件的统计）
        Map<String, Long> categoryStats = new HashMap<>();
        Map<String, Long> themeStats = new HashMap<>();

        int totalVideoCount = 0;

        for (BlVideoShootReqHd video : allVideos) {
            VideoVO vo = new VideoVO(video);
            int videoFileCount = vo.getVideoUrls().size();

            if (videoFileCount > 0) {
                totalVideoCount += videoFileCount;

                String shootCategory = video.getShootCategory();
                categoryStats.put(shootCategory, categoryStats.getOrDefault(shootCategory, 0L) + videoFileCount);

                if ("002".equals(shootCategory) && video.getTopicName() != null) {
                    themeStats.put(video.getTopicName(), themeStats.getOrDefault(video.getTopicName(), 0L) + videoFileCount);
                }
            }
        }

        Map<String, Object> stats = new HashMap<>();
        stats.put("totalVideos", totalVideoCount);
        stats.put("categoryStats", categoryStats);
        stats.put("themeStats", themeStats);

        return stats;
    }

    public List<String> getAvailableCategories() {
        return videoRepository.findAllActive()
                .stream()
                .map(BlVideoShootReqHd::getShootCategory)
                .distinct()
                .sorted()
                .collect(Collectors.toList());
    }

//    public List<String> getAvailableThemes() {
//        return videoRepository.findAllActive()
//                .stream()
//                .filter(v -> "002".equals(v.getShootCategory()))
//                .map(BlVideoShootReqHd::getTopicName)
//                .distinct()
//                .filter(Objects::nonNull)
//                .sorted()
//                .collect(Collectors.toList());
//    }


    public List<ThemeInfoVO> getAvailableThemes() {
        // 获取所有主题视频，按主题名称分组并统计数量
        Map<String, Long> themeCountMap = videoRepository.findAllActive()
                .stream()
                .filter(v -> "002".equals(v.getShootCategory())) // 主题视频
                .filter(v -> v.getTopicName() != null && !v.getTopicName().trim().isEmpty())
                .collect(Collectors.groupingBy(
                        BlVideoShootReqHd::getTopicName,
                        Collectors.counting()
                ));

        // 转换为ThemeInfoVO列表，按主题名称排序
        return themeCountMap.entrySet().stream()
                .map(entry -> new ThemeInfoVO(entry.getKey(), entry.getValue()))
                .sorted(Comparator.comparing(ThemeInfoVO::getName))
                .collect(Collectors.toList());
    }

    public List<VideoVO> getVideosByThemeName(String themeName) {
        return videoRepository.findAllActive()
                .stream()
                .filter(v -> "002".equals(v.getShootCategory()))
                .filter(v -> themeName.equals(v.getTopicName()))
                .map(VideoVO::new)
                .filter(VideoVO::hasValidVideos)
                .collect(Collectors.toList());
    }

}
